<template>
  <div class="wrapper" style="overflow: hidden;">
    <!-- 顶部 -->
    <top @filterSel="filter"></top>
    <ul class="list-out house-style" id="contact-style" v-show="index===0">
      <!--联系人/群-->
      <li v-for="item in rencentChats" v-if="item" @click.stop="goSession(item)"
          :class="!item.MsgFlag&&item.UnreadMsgCount>0?'userItem unread':'userItemHouse'">
        <!--最近联系人-->
        <mt-cell-swipe
          :right="[{content: '删除',style: { background: 'red', color: '#fff' },handler: () => deleteContact(item)}]"
          v-if="item.Type == 1 || item.type == 'C2C'">
          <img class="user-icon" :onerror="defaultImg" :src="item.C2cImage?item.C2cImage:c2cHead">
          <div class="userItemText">
            <div class="user">{{item.C2cNick?item.C2cNick:item.id}}
              <time>{{transTime(item.MsgTimeStamp,'')}}</time>
            </div>
            <p>{{item.MsgShow}}</p>
          </div>
        </mt-cell-swipe>
        <!--最近联系群-->
        <mt-cell-swipe
          :right="[{content: '删除',style: { background: 'red', color: '#fff' },handler: () => deleteContact(item)}]"
          v-else>
          <img class="user-icon" :onerror="defaultGroupImg" :src="item.GroupImage?item.GroupImage:groupHead">
          <div class="userItemText">
            <div class="user">{{item.GroupNick?item.GroupNick:item.id}}
              <time>{{transTime(item.MsgTimeStamp,'')}}</time>
            </div>
            <p>{{item.MsgShow}}</p>
          </div>
        </mt-cell-swipe>
      </li>
    </ul>

    <!-- 全部联系人-->
    <div class="house-style" v-show="index===1">
      <mt-index-list style="-webkit-overflow-scrolling: touch;">
        <mt-index-section v-for="(item,key) in alphabet" :key="key" :index="item.initial">
          <div v-for="(cell,key) in item.cells" :key="key" class="list" @click="toDetails(cell)">
            <img src="http://placekitten.com/200/198" alt="">
            <p>{{cell.name}}</p>
          </div>
        </mt-index-section>
      </mt-index-list>
    </div>
    <!-- 群聊-->
    <div class="house-style" v-show="index===2">群聊</div>
    <!-- tab -->
    <tab page="chat"></tab>
  </div>

</template>
<script>
  const NAMES = ['Aaron', 'Alden', 'Austin', 'Baldwin', 'Braden', 'Carl', 'Chandler', 'Clyde', 'David', 'Edgar', 'Elton', 'Floyd', 'Freeman', 'Gavin', 'Hector', 'Henry', 'Ian', 'Jason', 'Joshua', 'Kane', 'Lambert', 'Matthew', 'Morgan', 'Neville', 'Oliver', 'Oscar', 'Perry', 'Quinn', 'Ramsey', 'Scott', 'Seth', 'Spencer', 'Timothy', 'Todd', 'Trevor', 'Udolf', 'Victor', 'Vincent', 'Walton', 'Willis', 'Xavier', 'Yvonne', 'Zack', 'Zane'];
  import {checkStatus} from '../../assets/js/login';
  import {Toast, Popup, CellSwipe} from 'mint-ui';
  import Client from '../../assets/js/common';
  import convertMsgtoHtml from '../../assets/js/convertMsg';
  import Chat from '../../assets/js/chat';
  import c2cHead from '../../assets/img/my@3x.png';
  import groupHead from '../../assets/img/the@3x.png';
  import Top from './topSearch.vue'
  import Tab from './tabBar.vue'

  export default {
    data () {
      return {
        popupVisible: false,
        loginInfo: {},
        rencentChats: null,
        c2cHead,
        groupHead,
        transTime: Client.transTime,
        defaultImg: Client.defaultImg,
        defaultGroupImg: Client.defaultImg,
        index: 0, // tab index
        alphabet2: [],
        alphabet: [{
          cells: [{name: 'Aaron', url: 'http://www.baidu.com'}, {
            name: 'Alden',
            url: 'http://www.126.com'
          }, {name: 'Alfen', url: 'http://www.163.com'}], initial: 'A'
        },
          {
            cells: [{name: 'Baron', url: 'http://www.baidu.com'}, {
              name: 'Alden',
              url: 'http://www.126.com'
            }, {name: 'Alfen', url: 'http://www.163.com'}], initial: 'B'
          },
          {
            cells: [{name: 'Caron', url: 'http://www.baidu.com'}, {
              name: 'Alden',
              url: 'http://www.126.com'
            }, {name: 'Alfen', url: 'http://www.163.com'}], initial: 'C'
          },
          {
            cells: [{name: 'Daron', url: 'http://www.baidu.com'}, {
              name: 'Alden',
              url: 'http://www.126.com'
            }, {name: 'Alfen', url: 'http://www.163.com'}], initial: 'D'
          }]
      }
    },
    created () {
      checkStatus((loginInfo) => {
        this.loginInfo = loginInfo;
        this.getRencent();
      });
      'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').forEach(initial => {
        let cells = NAMES.filter(name => name[0] === initial);
        this.alphabet.push({
          initial,
          cells
        });
      });
    },
    mounted () {
      document.title = '会管家'
      this.setHeight();
      setTimeout(() => {
        let indexList = document.querySelector('.mint-indexlist-content').style
        indexList.marginRight = 0;
        indexList.paddingBottom = '1.8rem';
        indexList.boxSizing = 'border-box';
      }, 0)
    },
    components: {
      'mtCellSwipe': CellSwipe, Top, Tab
    },
    methods: {
      // 链接地址跳转
      goLink (link) {
        this.$router.push(link);
      },
      //获取未读c2c消息
      getMsgNotify () {
        webim.syncMsgs(
          resp => {
            let sessMap = webim.MsgStore.sessMap();
            if (this.rencentChats) {
              for (let i in sessMap) {
                let items = sessMap[i]._impl;
                this.rencentChats.forEach((ele, i) => {
                  if (items.id == ele.id) {
                    ele.UnreadMsgCount = items.unread;
                  }
                });
              }
            }
            //好友缺少的字段或信息从好友资料里拿
            Chat.getAllFriend(this.loginInfo.identifier).then(res => {
              if (res == null) return;
              this.infoMap = res.InfoItem;
              //console.log('this.infoMap',this.infoMap);
              Client.setStore('infoMap', res.InfoItem);
              if (this.rencentChats) {
                this.getFriendInfo(this.rencentChats);
              }
            });
          },
          err => {
            Client.errInfo();
            //alert(err.ErrorInfo);
          }
        );
      },
      //获取最近联系人
      getRencent () {
        webim.getRecentContactList({
          'Count': 50 //最近的会话数 ,最大为100
        }, resp => {
          let rencentOri = resp.SessionItem;
          //为了之后便于处理，将私聊To_Account以及群聊ToAccount统一成id字段
          let hasGroupMsg = false;
          if (rencentOri) {
            this.rencentChats = rencentOri.filter((item) => {
              if (item.Type == 1) {
                item.id = item.To_Account;
              } else {
                item.id = item.ToAccount;
                hasGroupMsg = true;
              }
              //云通信会将一周前的聊天记录全清空,此时过滤零记录联系人
              return item.MsgTimeStamp !== 0;
            });
            //如果联系人中存在群组,另外处理群接收但不提示消息的状态
            if (hasGroupMsg) {
              Chat.getMyGroup(this.loginInfo.identifier).then(resp => {
                //console.log('群组资料',resp);
                this.myGroupInfo = resp;
                //设置了接收但不提示消息的群
                let groupAcceptMsg = [];
                resp.forEach((item) => {
                  if (item.SelfInfo && item.SelfInfo.MsgFlag == 'AcceptNotNotify') {
                    this.rencentChats.forEach((val) => {
                      if (val.ToAccount == item.GroupId) {
                        val.MsgFlag = 'AcceptNotNotify';
                        groupAcceptMsg.push(item.GroupId);
                        //console.log('匹配到的群组',val)
                      }
                    })
                  }
                });
                this.groupMsgFlag = groupAcceptMsg;
              });
            }
          }
          this.getMsgNotify();
          //业务处理
        }, resp => {
          Client.errInfo();
          console.log(resp)
          //错误回调
        });
      },
      //删除最近联系人
      deleteContact (item) {
        //Type最近联系人类型,type未读消息联系人类型
        let newType = item.Type || item.type;
        if (newType == 'C2C') {
          newType = 1;
        }
        if (newType == 'GROUP') {
          newType = 2;
        }
        let dataContact = {
          'To_Account': item.id,
          'chatType': newType
        }
        webim.deleteChat(
          dataContact,
          resp => {
            //要操作的数据对象（最近联系人还是未读信息联系人）
            if (item.UnreadMsgCount > 0) {
              //假如是未读消息联系人,设置消息已读
              let selSess = webim.MsgStore.sessByTypeId(item.type, item.id);
              webim.setAutoRead(selSess, true, true);
            }
            this.rencentChats.forEach((ele, i) => {
              if (ele.id == item.id) {
                this.rencentChats.splice(i, 1);
              }
            });
            //console.log('删除联系人成功',dataContact);
          },
          resp => {
            Client.errInfo();
            console.log('删除联系人失败', resp);
          }
        );
      },
      //跳转未读消息聊天
      goNews (item) {
        this.$router.push({path: "/session", query: {id: item.id, selType: item.type}});
      },
      //跳转最近联系人聊天
      goSession (item) {
        let newTypes = 'C2C';
        if (item.Type == 2 || item.type == 'GROUP') {
          newTypes = 'GROUP';
        }
        this.$router.push({path: "/session", query: {id: item.id, selType: newTypes}});
      },
      compare (property) {
        return (obj1, obj2) => {
          let value1 = obj1[property],
            value2 = obj2[property];
          return value2 - value1;
        }
      },
      getFriendInfo (oriArr) {
        let test88 = oriArr instanceof Array;
        if (this.infoMap) {
          if (oriArr instanceof Array) {
            oriArr.forEach((val) => {
              if (val.Type == 1) {
                this.matchInfo(val);
              }
            });
          } else {
            this.matchInfo(oriArr);
          }
        }
      },
      //从缓存好友表里匹配数据
      matchInfo (val) {
        this.infoMap.forEach((item, index) => {
          if (item.SnsProfileItem) {
            item.SnsProfileItem.find((list) => {
              if (item.Info_Account == val.id) {
                if (list.Tag == 'Tag_Profile_IM_Image') {
                  val.C2cImage = list.Value;
                } else if (list.Tag == 'Tag_Profile_IM_Nick') {
                  val.C2cNick = list.Value;
                }
              }
            });
          }
        });
      },
      setHeight () {
        let contentH = document.querySelectorAll('.house-style');
        [...contentH].forEach(function (item) {
          item.style.height = window.innerHeight + 'px'
        })
        // let top = document.querySelector('.fix-block').offsetHeight;
        // let tabBar = document.querySelector('.tab-bar').offsetHeight;
        // contentH.style.height = window.innerHeight-top-tabBar+ 'px';
        // contentH.style.height = window.innerHeight+ 'px';
      },
      // 搜索
      toSearch () {
        this.$router.push('/search')
      },
      // tab 切换
      filter (val) {
        console.log(val);
        this.index = val;
      },
      // 链接跳转
      toDetails (val) {
        window.location.href = val.url
      }
    },
    watch: {
      'loginInfo.onMsgNotify': function (val) {
        if (val == null) {
          return
        } else {
          //console.log('监听回来的消息',val);
          let unReadObj = val.sess._impl;
          let transObj = convertMsgtoHtml(val);
          unReadObj.MsgShow = Client.transNews(transObj);
          unReadObj.MsgTimeStamp = unReadObj.time;
          //监听回来的未读群消息unread记录为0?
          unReadObj.UnreadMsgCount = 1;
          if (unReadObj.type == 'C2C') {
            //console.log('c2c2',unReadObj);
            this.getFriendInfo(unReadObj);
          } else {
            unReadObj.GroupNick = unReadObj.name;
            //如果存在有群设置了接收但不提示消息
            if (this.groupMsgFlag) {
              this.groupMsgFlag.forEach((item, index) => {
                if (unReadObj.id == item) {
                  unReadObj.MsgFlag = 'AcceptNotNotify';
                }
              })
            }
            //检查替换群头像
            if (this.myGroupInfo) {
              this.myGroupInfo.forEach((item) => {
                if (item.GroupId == unReadObj.id) {
                  unReadObj.GroupImage = item.FaceUrl;
                }
              })
            }
          }
          //console.log("处理后的unReadObj",unReadObj);
          //完全没任何数据直接添加
          if (!this.rencentChats) {
            this.rencentChats = [];
            //console.log('初始回来的信息',unReadObj);
            this.rencentChats.push(unReadObj);
          } else {
            let hasExist = this.rencentChats.find((value, index, arr) => {
              return value.id == unReadObj.id;
            });
            if (typeof hasExist == 'undefined') {
              this.rencentChats.unshift(unReadObj);
            } else {
              this.rencentChats.forEach((ele, i) => {
                if (unReadObj.id == ele.id) {
                  this.rencentChats.splice(i, 1, unReadObj);
                }
              });
              //sort
              this.rencentChats.sort(this.compare("MsgTimeStamp"));
            }
          }
        }
      },

    }
  }

</script>
<style lang="less">
  .userItemHouse {
    .mint-cell-swipe {
      width: 100%;
      background: none !important;
    }
    .mint-cell-wrapper .mint-cell-title {
      display: none;
    }
    .mint-cell-wrapper .mint-cell-value {
      margin-left: .16rem;
      border-bottom: .005rem solid #dedede;
    }
    .mint-cell-wrapper {
      padding: 0;
      background-image: none;
    }
    .mint-cell-swipe-buttongroup .mint-cell-swipe-button {
      padding: 0 .2rem;
      font-size: .14rem;
      line-height: .64rem;
      height: .64rem;
      margin-top: .01rem;
    }
    &.unread .mint-cell-value:after {
      display: block;
      content: '';
      width: .06rem;
      height: .06rem;
      background: #EC5656;
      border-radius: .03rem;
      position: absolute;
      top: .12rem;
      left: .5rem;
    }
  }
</style>
<style lang="less" scoped>
  .wrapper {
    .wrap {
      right: 0.08rem !important;
      top: 1.38rem !important;
      background: none;
      .menuWrap {
        width: 1.3rem;
        position: relative;
        &:before {
          width: 0;
          height: 0;
          display: block;
          content: '';
          border-width: .06rem;
          border-style: solid;
          border-color: transparent transparent #fff transparent;
          position: absolute;
          right: .1rem;
          top: -.12rem;
        }
        .menu {
          width: 1.3rem;
          background-color: white;
          border-radius: .03rem;
          overflow: hidden;
          .menuLi {
            height: 0.39rem;
            border-bottom: 1px solid #E1E1E1;
            display: flex;
            align-items: center;
            img {
              width: 0.14rem;
              height: 0.14rem;
              margin-left: 0.17rem;
              margin-right: 0.1rem;
            }
          }
          .menuLiLast {
            border: none;
          }

        }
      }
    }

    .header {
      width: 100%;
      height: 0.5rem;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      font-size: 0.16rem;
      border-bottom: 1px solid #f4f4f4;
      background-color: white !important;
      img {
        width: 0.2rem;
        height: 0.14rem;
        position: absolute;
        right: 0.15rem;
        top: 50%;
        margin-top: -0.07rem;
      }
    }
    .list-out {
      overflow-y: scroll;
      -webkit-overflow-scrolling: touch;
      background: #fff;
      .userItemHouse {
        height: 0.64rem;
        /*margin: 0 0.13rem;*/
        display: flex;
        align-items: center;
        background: #fff;
        img {
          width: 0.44rem;
          height: 0.44rem;
          border-radius: 50%;
        }
        .userItemText {
          width: 2.9rem;
          height: 0.65rem;
          margin-left: 0.1rem;
          border-bottom: 1px solid #E1E1E1;
          padding: 0.12rem 0;
          box-sizing: border-box;
          .user {
            height: 0.2rem;
            line-height: 0.2rem;
            color: #4A4A4A;
            font-size: 0.14rem;
            overflow: hidden;
            time {
              float: right;
              font-size: 11px;
              color: #818181;
            }
          }
          p {
            height: 0.2rem;
            line-height: 0.2rem;
            color: #818181;
            font-size: 12px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
        &:last-child {
          .userItemText {
            border: 0;
          }
        }
      }
    }

  }

  .house-style {
    padding-bottom: .49rem;
    padding-top: 1.14rem;
    box-sizing: border-box;
    background: #fff;
  }

  // 修改联系人样式
  #contact-style {
    .user-icon {
      width: .4rem;
      height: .4rem;
    }
    .user {
      font-size: .16rem;
      color: #333333;
      height: .225rem;
      line-height: .225rem;
      time {
        font-size: .12rem;
        color: #999999;
      }
    }
    .userItemText {
      margin-left: .12rem;
      border-bottom: none;
      p {
        font-size: .12rem;
        line-height: .165rem;
        height: .165rem;
        color: #999;
      }
    }
  }
</style>
